<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="点赞数" prop="likeCount">
        <el-input
          v-model="queryParams.likeCount"
          placeholder="请输入点赞数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="dictType">
        <el-select v-model="queryParams.dictType" placeholder="请选择类型" clearable>
          <el-option
            v-for="dict in dict.type.sys_resource_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="资源链接" prop="url">
        <el-input
          v-model="queryParams.url"
          placeholder="请输入资源链接"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:article:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:article:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:article:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:article:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文章id" align="center" prop="articleId" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="点赞数" align="center" prop="likeCount" />
      <el-table-column label="类型" align="center" prop="dictType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_resource_type" :value="scope.row.dictType"/>
        </template>
      </el-table-column>
      <el-table-column label="文章介绍" align="center" prop="introduce" />
      <el-table-column label="资源链接" align="center" prop="url" />
      <el-table-column label="文章内容" align="center" prop="content" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:article:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:article:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文章查询对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="标题图片" prop="imgurl">
          <el-upload
          :action="uploadUrl"
          :before-upload="handleBeforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          name="file"
          :show-file-list="false"
          >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          <img :src="this.form.imgurl" class="linshi">
        </el-form-item>
        <el-form-item label="链接" prop="url">
          <el-input v-model="form.url" placeholder="请输入链接" />
        </el-form-item>
        <el-form-item label="点赞数" prop="likeCount">
          <el-input v-model="form.likeCount" placeholder="请输入点赞数" />
        </el-form-item>
        <el-form-item label="类型" prop="dictType">
          <el-select v-model="form.dictType" placeholder="请选择类型">
            <el-option
              v-for="dict in dict.type.sys_resource_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="labelId">  
          <el-select v-model="myselect" placeholder="请选择标签"  multiple @change="handleSelectChange">
            <el-option v-for="option in options" :value="option.labelName" :key="option.labelId" >  
              {{ option.labelName }}  
            </el-option>
          </el-select>
       </el-form-item>  
        <el-form-item label="文章介绍" prop="introduce">
          <el-input v-model="form.introduce" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="文章内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="点击量" prop="clicknum">
          <el-input v-model="form.clicknum" placeholder="请输入点击量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listArticle, getArticle, delArticle, addArticle, updateArticle } from "@/api/system/article";
import { listLabel,tagsList } from "@/api/system/label";
import {batchInsert,removeByArticleId} from "@/api/system/al";
import { getToken } from "@/utils/auth";

export default {
  name: "Article",
  dicts: ['sys_resource_type'],
  data() {
    return {
      myselect01:[],
      myselect: [], // 存储选中的值  
      options: [ // 下拉选项  
      ], 
      selectedKeys:[],
      CurrentID:0,

      //新增代码
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      fileList: [{name: '封面图', url: 'uploadUrl'}],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文章查询表格数据
      articleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        likeCount: null,
        dictType: null,
        introduce: null,
        url: null,
        content: null,
        labelId:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        dictType: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ],
        introduce: [
          { required: true, message: "文章介绍不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询文章查询列表 */
    getList() {
      this.loading = true;
      listArticle(this.queryParams).then(response => {
        this.articleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        articleId: null,
        title: null,
        createTime: null,
        createBy: null,
        likeCount: null,
        dictType: null,
        introduce: null,
        url: null,
        content: null,
        feedbackChose: null,
        clicknum: null,
        imgurl:null
      };
      this.selected=null,
      this.options=null,
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.articleId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.myselect=[];
      this.selectedKeys=[];
      this.options = [];
      this.open = true;
      this.title = "添加文章查询";
      listLabel(this.queryParams).then(response => {
        console.log(response.data);
        this.options = response.data;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.myselect=[];
      this.myselect01=[];
      this.selectedKeys=[];
      this.options = [];
      const articleId = row.articleId || this.ids;
      this.CurrentID = articleId;
      getArticle(articleId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文章查询";
      });

      tagsList({articleId:articleId}).then(response=>{
        console.log(response.data);
        response.data.forEach(item => {  
        // 将每个对象的labelName属性添加到myselect数组中  
          this.myselect.push(item.labelName);  
          this.myselect01.push(item.labelName);
        });  
        console.log( this.myselect);
      })

      listLabel(this.queryParams).then(response => {
        console.log(response.data);
        this.options = response.data;
      });
     
      
      
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.articleId != null) {
            //排除不必要的请求
            console.log(this.myselect01);
            console.log(this.myselect);
            let flag = true;
            if(this.myselect01.length !== this.myselect.length) {  
              flag=false;
              console.log("111");
            }  
            if(flag){
              for (let i = 0; i < this.myselect01.length; i++) {  
              if (this.myselect01[i] !== this.myselect[i]) {  
                flag = false;
                console.log("222");
                break;
                }  
              }   
            }
            if(flag == false){
              //半段是否增加了标签，如果已选择为空直接删除
              console.log(this.selectedKeys);
              if(this.selectedKeys.length>0){
                batchInsert(this.selectedKeys);
              }else{
                removeByArticleId(this.CurrentID);
              }
            }

            
            updateArticle(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArticle(this.form).then(response => {
              // batchInsert(this.selectedKeys);
              // myselect
              this.selectedKeys = this.myselect.map(labelName => { 
              const articleId = response.data;
              const option = this.options.find(opt => opt.labelName === labelName);  
              return option ? { labelId: option.labelId, articleId } : null; // 如果没有找到匹配的选项，返回 null  
              });  
              console.log(this.selectedKeys);
              if(this.selectedKeys.length>0){
                batchInsert(this.selectedKeys);
              }
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const articleIds = row.articleId || this.ids;
      this.$modal.confirm('是否确认删除文章查询编号为"' + articleIds + '"的数据项？').then(function() {
        if(delArticle(articleIds)){
          return removeByArticleId(articleIds);
        }else{
          return false;
        }
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/article/export', {
        ...this.queryParams
      }, `article_${new Date().getTime()}.xlsx`)
    },

     //新增代码
     // 上传前校检格式和大小
     handleBeforeUpload(file) {
      const type = ["image/jpeg", "image/jpg", "image/png", "image/svg"];
      const isJPG = type.includes(file.type);
      // 检验文件格式
      if (!isJPG) {
        this.$message.error(`图片格式错误!`);
        return false;
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    handleUploadSuccess(res, file) {
      // 如果上传成功
      if (res.code == 200) {
        console.log(process.env.VUE_APP_BASE_API + res.fileName);
        this.form.imgurl=process.env.VUE_APP_BASE_API + res.fileName;
      } else {
        this.$message.error("111图片插入失败");
      }
    },
    handleUploadError() {
      this.$message.error("图片插入失败");
    },
    handleSelectChange(value) {  
    console.log("触发了")
    this.selectedKeys = value.map(labelName => { 
      const articleId = this.CurrentID ;
      const option = this.options.find(opt => opt.labelName === labelName);  
      return option ? { labelId: option.labelId, articleId } : null; // 如果没有找到匹配的选项，返回 null  
    });  
  }  
  }
};
</script>
 
<style scoped>
.linshi{
  width: 100%;
  height: 100px;
}
</style>
